<template>
	<view class="page-body bg-white" :class="[app.setCStyle()]">
		<u-navbar :is-back="false" title="" title-width="100%">
			<view class="u-p-l-20 u-p-r-20 w100 nav-title">
				<view class="left-wrap">
					<u-icon @click="app.goPage(-1)" class="fs36" name="arrow-left"></u-icon>
					<u-icon @click="app.goPage('/')" class="fs36 u-m-l-20" name="home"></u-icon>
				</view>
				<view class="u-text-center fs36">{{settings.site_name}}</view>
			</view>
		</u-navbar>
		
		<view v-if="isWXLogin" class="wx-login p50">
			<view class="u-m-t-80 u-p-t-80 u-text-center">
				<view class="fs40 u-p-t-80">微信授权登录</view>
				<view class="fs26 color-99 mt10">请微信授权您的昵称、头像等</view>
			</view>
			<view class="u-m-t-80">
				<u-button  size="default" hover-class="none"  class=" mt40 defaultbtn" shape="circle" @click="wxLogin">微信授权登录</u-button>
			</view>
		</view>
		
		<view v-else class="mobile-login p50 bg-white">
			
			<!-- <view class="top_logo" style="width: 150rpx;height: 150rpx;margin: 0rpx auto;">
				<u-image width="100%" height="100%"  :src="baseUrl+settings.logo" shape="circle"></u-image>
			</view> -->
			<view class="title">
				<view class="fs40">{{settings.site_name}}登录</view>
				<view class="fs26 color-99 u-m-t-10">账号密码登录, 或者微信登录</view>
			</view>
			<!-- <text class="block fs36 font-w600 mt30 text-center">{{settings.site_name}}</text> -->
			<u-form :model="model" ref="uForm" :errorType="errorType" class="mt80">
				<u-form-item left-icon="../../../static/public/images/login-mobile.png"
					:left-icon-style="leftIconStyle"
					:label-position="labelPosition"
					label="手机" 
					prop="mobile">
					<u-input :border="border" placeholder="请输入您的手机号" v-model="model.mobile" type="number"></u-input>
				</u-form-item>
				<!-- <view v-if="model.login_type==0"> -->
					<u-form-item v-if="model.login_type==0"
						left-icon="../../../static/public/images/login-password.png" 
						:left-icon-style="leftIconStyle"
						:label-position="labelPosition" 
						label="密码" 
						prop="password">
						<u-input :password-icon="false" :border="border" type="password" v-model="model.password" placeholder="请输入您的密码"></u-input>
					</u-form-item>
			
					<!-- <u-form-item :label-position="labelPosition" label="记住密码"  prop="remember" label-width="150">
						<u-switch v-model="model.remember" slot="right" active-color="#fe0079"></u-switch>
					</u-form-item> -->
				<!-- </view> -->
				<u-form-item  v-if="model.login_type==1" :label-position="labelPosition" label="验证码"
				 prop="code" label-width="150">
					<u-input :border="border" placeholder="请输入验证码" v-model="model.code" type="text"></u-input>
					<button slot="right" type="success" size="mini" class="bg-base color-ff" @click="getCode">{{codeTips}}</button>
				</u-form-item>
				<u-form-item v-if="showVerify" :label-position="labelPosition" label="图形验证码" prop="verifyCode" label-width="150">
					<u-input :border="border" placeholder="输入验证码" v-model="model.verifyCode" type="text"></u-input>
					<u-image width="200rpx" height="80rpx" :src="verifyUrl" @click="changeVerifyUrl"></u-image>
				</u-form-item>
				<view class=" color-base smll pt40 u-border-top">
					<!-- <view class="flex_bd">
						<text v-if="settings.sms_public_login"  @click="changeLogin">{{logintype}}</text>
					</view> -->
					<view class="flex_bd">
						<text v-if="settings.sms_public_login"  @click="goForget">忘记密码？</text>
					</view>
					<view v-if="settings.sms_public_forget_password" @click="goRegister">新用户注册</view>
				</view>
				<u-button size="default" hover-class="none" class="defaultbtn mt40" shape="circle"  @click="submit">登录</u-button>
				<!-- #ifdef MP-WEIXIN -->
				<u-button  size="default" hover-class="none"  class=" mt40 defaultbtn" shape="circle" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">手机授权登录</u-button>
				<!-- #endif -->
				
				<!-- <view v-if="settings.register_status == 1" class="mt40 clearfix  text-center">
					<view @click="goRegister">还没有帐号，<text class="base-color">立即注册</text></view>
				</view> -->
				<view class="mt50 text-center fs26 color-99">
					技术支持@{{settings.copyright}}
				</view>
				<u-verification-code seconds="60" ref="uCode" @change="codeChange"></u-verification-code>
			</u-form>
			
			<view v-if="isWeixin" class="wxLogin" @click="isWXLogin = true">
				<u-icon label="微信登录" label-pos="bottom" label-color="#86869C" name="weixin-circle-fill" color="#09BB07" size="80"></u-icon>
			</view>
		</view>
		
	</view>
</template>

<script>
	let that = this;
	
	export default {
		data() {
			return {
				settings: uni.getStorageSync('setting'),
				baseUrl:this.config.baseUrl,
				returnUrl:'',
				logintype: '短信登录',
				verifyUrl: '',
				showVerify: false,
				model: {
					mobile: '',//uni.getStorageSync("loginMobile"),
					code: '',
					password: '',//uni.getStorageSync("loginPassword"),
					login_type: 0,
					remember: false, //uni.getStorageSync("loginPassword") ? true : false,
					verifyCode: '',
					is_reg: 0,
				},
				pwrules: {
					mobile: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change，二者之间用英文逗号隔开
							trigger: ['change', 'blur'],
						}
					],
					password: [{
							required: true,
							message: '请输入密码',
							trigger: ['change', 'blur'],
						},
						{
							min: 8,
							message: '密码不能少于8个字符',
							trigger: 'change',
						}
					]
				},
				msmrules: {
					mobile: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change，二者之间用英文逗号隔开
							trigger: ['change', 'blur'],
						}
					],
					code: [{
							min: 6,
							required: true,
							message: '请输入6位验证码',
							trigger: ['change', 'blur'],
						},
						{
							type: 'number',
							message: '验证码只能为数字',
							trigger: ['change', 'blur'],
						}
					]
				},
				rulesgetCode: {
					mobile: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								// 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change，二者之间用英文逗号隔开
							trigger: ['change', 'blur'],
						}
					]
				},
				border: false,
				check: false,
				labelPosition: 'top',
				codeTips: '',
				errorType: ['toast'],
				leftIconStyle: {width:'32rpx',height:'43rpx',margin:'15rpx 10rpx 0 0'},
				isWeixin: navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1,
				isWXLogin: navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1,
				options: {}
			};
		},
		onLoad(options) {
			if (options.scene){//获取小程序的场景值，用于获取分享者的token
				let scene = options.scene.split('_');
				uni.setStorageSync("share_token",scene[0]);
			}
			if (typeof(options.returnUrl) == 'undefined'){
				this.returnUrl = uni.getStorageSync("loginReturnUrl");
			}else{
				this.returnUrl = options.returnUrl;
				uni.setStorageSync("loginReturnUrl",options.returnUrl);
			}
			options.auto_login = 0;//在登陆页面中获取open_id,不执行自动登陆
			this.options = options;
			if (options.code){
				this.app.getWxOauthOpenId(this,options, true);//默认只有初次打开时触发获取openid,退出登陆后后清理openid后，再访问登陆页重新获取
			}
			if(options.no_wx_login == 1) this.isWXLogin = false;
			if(options.is_reg == 1) this.model.is_reg = 1;
			this.verifyUrl = this.config.baseUrl + '/index.php/publics/api.index/verify/session_id/' + uni.getStorageSync("session_id");
		},
		computed: {
			borderCurrent() {
				return this.border ? 0 : 1;
			},
		},
		onShow() {
			uni.removeStorageSync("isNotLoginTip");//未登陆提示，此值会限制网络请求
		},
		onReady() {
			// #ifndef MP-WEIXIN
			this.$refs.uForm.setRules(this.pwrules);
			// #endif
		},
		methods: {
			wxLogin(){
				this.app.getWxOauthOpenId(this, this.options, true);
			},
			submit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						uni.setStorageSync("loginMobile", this.model.mobile); //记住手机号
						if (this.model.remember == true) {
							uni.setStorageSync("loginPassword", this.model.password); //记住密码
						} else {
							try {
								uni.removeStorageSync('loginPassword'); //销毁记住密码
							} catch (e) {}
						}
						this.$u.post('member/api.passport/login', this.model).then(res => {
							if (res.code < 0) {
								this.showVerify = res.data.showVerify;
								this.$u.toast(res.msg);
								return false;
							}
							this.loginGo(res);
						})
					} else {
						console.log('验证失败');
					}
				});
			},
			getPhoneNumber (e) {
				//小程序手机授权登陆
				if (e.detail.errMsg == "getPhoneNumber:ok") {
				    this.$u.post('weixin/api.index/loginByMpPhone', {
						iv:e.detail.iv,
						encryptedData:e.detail.encryptedData,
						openid:this.app.getWxOpenId()
					}).then(res => {
						if (res.data.must_reg == 1){
							let phoneNumber = res.data.phoneNumber;
							uni.showModal({
								title: '提示',
								content: '手机号码未注册会员',
								showCancel: true,
								confirmText: '立即注册',
								cancelText: '暂不注册',
								success: function(res) {
									if (res.confirm) {
										uni.setStorageSync("wxEncryptedData", e.detail); //记住微信授权加密信息
										uni.redirectTo({
											url: `register?phoneNumber=${phoneNumber}`
										});
									}
								}
							});
							return false;
						}
						if (res.data.token){
							this.loginGo(res);
						}
					})
				}
			 },
			loginGo(res){
				//登录成功后执行
				this.app.setAuthCode(res.data.token);
				if (typeof(this.returnUrl) == 'undefined') { //未读取到页面信息
					uni.redirectTo({
					    url: '/pages/member/center/index'
					});
					return false;
				}
				uni.redirectTo({
					url:'/'+decodeURIComponent(this.returnUrl),
				});
			},
			changeLogin(text) {
				if (this.model.login_type == 0) {
					this.logintype = '密码登录';
					this.model.login_type = 1;
					this.$refs.uForm.setRules(this.msmrules);
				} else {
					this.logintype = '短信登录';
					this.model.login_type = 0;
					this.$refs.uForm.setRules(this.pwrules);
				}
			},
			changeVerifyUrl() {
				if (this.verifyUrl.indexOf('rand=') > -1) {
					this.verifyUrl = this.verifyUrl.substr(0, this.verifyUrl.length - 19);
				}
				this.verifyUrl += '?rand=' + new Date().getTime();
			},
			codeChange(text) {	
				this.codeTips = text;
			},
			// 获取验证码
			getCode() {
				if (this.$refs.uCode.canGetCode) {
					this.$refs.uForm.setRules(this.rulesgetCode);
					this.$refs.uForm.validate(valid => {
						if (valid) {	
							// 向后端请求验证码
							uni.showLoading({
								title: '正在获取验证码',
								mask: true
							})
							this.$u.get('publics/api.sms/sendCode', {
								'type': 'login',
								'mobile': this.model.mobile
							}).then(res => {
								uni.hideLoading();
								// 这里此提示会被this.start()方法中的提示覆盖
								if (res.data.code){
									this.$u.toast('测试状态，验证码自动填充');
									this.model.code = res.data.code;
								}else{
									this.$u.toast('验证码已发送');
								}
								this.user_exist = res.data.user_exist;
								// 通知验证码组件内部开始倒计时
								this.$refs.uCode.start();
							})
						}
					});
				} else {
					this.$u.toast('倒计时结束后再发送');
				}
			},
			
			goForget() {
				uni.navigateTo({
					url: '/pages/member/passport/forget'
				});
			},
			goRegister() {
				uni.navigateTo({
					url: '/pages/member/passport/register'
				});
			}
		}
	}
</script>
<style lang="scss">
	.nav-title{
		position: relative;
		.left-wrap{
			position: absolute;
			top: 0;
			left: 20rpx;
		}
	}
	.wxLogin{
		width: 120rpx;
		height: 130rpx;
		text-align: center;
		margin: 100rpx auto 0;
	}
</style>
